import os
import re
import hashlib
from flask import Blueprint, request, jsonify, current_app
from app.extensions import db  # 从扩展中导入数据库实例
from app.models import User  # 假设已定义User模型

# 创建用户相关蓝图
user_bp = Blueprint('user', __name__, url_prefix='/api/v1')

def hash_password(password):
    """密码加密（使用SHA-256加盐）"""
    salt = os.urandom(16)  # 生成16字节随机盐值
    password_bytes = password.encode('utf-8')
    hash_obj = hashlib.sha256(salt + password_bytes)
    return salt + hash_obj.digest()  # 返回二进制数据（盐+哈希，共48字节）

def verify_password(stored_hash, input_password):
    """验证密码（用于后续登录功能）"""
    salt = stored_hash[:16]  # 提取前16字节作为盐
    stored_hash_value = stored_hash[16:]  # 提取后32字节作为哈希值
    input_bytes = input_password.encode('utf-8')
    input_hash = hashlib.sha256(salt + input_bytes).digest()
    return input_hash == stored_hash_value

@user_bp.route('/user/register', methods=['POST'])
def register():
    """用户注册接口"""
    data = request.get_json()
    if not data:
        return jsonify({
            "code": 400,
            "message": "注册失败",
            "errors": {"general": "请提供JSON格式的请求数据"}
        }), 400

    # 提取并验证参数
    username = data.get('username', '').strip()
    password = data.get('password', '').strip()
    errors = {}

    # 用户名验证
    if not username:
        errors['username'] = "用户名不能为空"
    elif not 3 <= len(username) <= 20:
        errors['username'] = "用户名长度必须在3-20位之间"
    elif not re.match(r'^[a-zA-Z0-9_]+$', username):
        errors['username'] = "用户名只能包含字母、数字和下划线"

    # 密码验证
    if not password:
        errors['password'] = "密码不能为空"
    elif len(password) < 8:
        errors['password'] = "密码长度至少8位"
    elif not (re.search(r'[A-Za-z]', password) and re.search(r'[0-9]', password)):
        errors['password'] = "密码必须包含字母和数字"

    if errors:
        return jsonify({
            "code": 400,
            "message": "注册失败",
            "errors": errors
        }), 400

    # 检查用户名是否已存在
    existing_user = User.query.filter_by(username=username).first()
    if existing_user:
        return jsonify({
            "code": 400,
            "message": "注册失败",
            "errors": {"username": "用户名已被占用"}
        }), 400

    # 创建新用户
    try:
        password_hash = hash_password(password)
        new_user = User(
            username=username,
            password_hash=password_hash  # 存储二进制哈希值
        )
        db.session.add(new_user)
        db.session.commit()

        return jsonify({
            "code": 200,
            "message": "注册成功，请登录",
            "data": {"username": username}
        }), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"注册失败: {str(e)}")
        return jsonify({
            "code": 500,
            "message": "服务器错误，请稍后再试"
        }), 500





# {
#   "username": "test_user",
#   "password": "Test123456"
# }